<script lang="ts" setup>
import type { SystemUserApi } from '#/api';

import { computed, nextTick, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Spin } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createUser, getUserById, updateUser } from '#/api/system';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emits = defineEmits(['success']);

const formData = ref<SystemUserApi.User>();
const loading = ref(false);

const [Form, formApi] = useVbenForm({
  schema: useFormSchema(),
  showDefaultActions: false,
});

const id = ref();
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();

    // 移除确认密码字段
    delete values.confirmPassword;

    drawerApi.lock();
    (id.value
      ? updateUser({ ...values, id: id.value } as SystemUserApi.User)
      : createUser(values as SystemUserApi.User)
    )
      .then(() => {
        emits('success');
        drawerApi.close();
      })
      .catch(() => {
        drawerApi.unlock();
      });
  },

  async onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<SystemUserApi.User>();
      formApi.resetForm();

      if (data?.id) {
        formData.value = data;
        id.value = data.id;

        // 加载用户数据
        await loadUserData(data.id);
      } else {
        id.value = undefined;
      }

      // Wait for Vue to flush DOM updates (form fields mounted)
      await nextTick();
      if (data) {
        await formApi.setValues(data);
      }
    }
  },
});

async function loadUserData(userId: number | string) {
  try {
    loading.value = true;
    const data = await getUserById(userId);
    formData.value = data;

    // 设置表单值，确保角色数据正确设置
    await formApi.setValues({ ...data, role_ids: data.role_ids });
  } finally {
    loading.value = false;
  }
}

const getDrawerTitle = computed(() => {
  return formData.value?.id
    ? $t('common.edit', [$t('system.user.name')])
    : $t('common.create', [$t('system.user.name')]);
});
</script>

<template>
  <Drawer :title="getDrawerTitle">
    <Spin :spinning="loading">
      <Form />
    </Spin>
  </Drawer>
</template>
